package com.lzx.iteam.net;

import android.content.Context;
import android.os.Message;
import com.lzx.iteam.bean.ChatContact;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;


/**
 * Created by shijunting on 15-3-11.
 */
public class ChatUserInfoMsg extends CcMsgStructure {


    private Message mmCallback;
    private CloudDBOperation cloudDBOperation;

    public ChatUserInfoMsg(Message callback, Context context) {
        mmCallback = callback;
        cloudDBOperation = new CloudDBOperation(context);

    }

    @Override
    public void onReceive(JSONObject data) {
        ArrayList<ChatContact> chatContacts = new ArrayList<>();
        try {
            JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            JSONArray jsonArray = jsonObject.getJSONArray("info");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject info = jsonArray.getJSONObject(i);
                ChatContact chatContact = new ChatContact();
                chatContact.userName = info.getString("user_name");
                chatContact.userImg = info.getString("avatar");
                chatContact.userId = info.getString("user_id");
                if (cloudDBOperation.findUserMsgById(chatContact.userId).userId == null) {
                    cloudDBOperation.insertUserMsg(chatContact);
                } else {
                    ChatContact chatContact1 = cloudDBOperation.findUserMsgById(chatContact.userId);
                    if ((!chatContact1.userImg.equals(chatContact.userImg)) || (!chatContact1.userName.equals(chatContact.userName))) {
                        cloudDBOperation.updataUserMsg(chatContact.userId, chatContact1);
                    }
                }
                chatContacts.add(chatContact);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (mmCallback != null)

        {
            mmCallback.obj = chatContacts;
            mmCallback.arg1 = 0;
            mmCallback.sendToTarget();
            return;
        }

    }

    @Override
    public void onError(int error, Object ret) {
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }
        }
        if (mmCallback != null) {
            mmCallback.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mmCallback.obj = errorMsg;
            } else {
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }
    }
}
